import React, { useContext } from "react";
import RcCheckbox from "rc-checkbox";
import classnames from "classnames";
import { ThemeContext } from "../theme";

import type { CheckboxProps, CheckboxGroupProps } from "./type";

export default Checkbox;

Checkbox.CheckboxGroup = Group;

function Checkbox({
  style,
  className,
  border,
  value,
  checked,
  label,
  disabled,
  onChange,
}: CheckboxProps) {
  const { fontSize } = useContext(ThemeContext);
  return (
    <label
      className={classnames("ct0-checkbox-single", {
        "ct0-checkbox-border": border,
        "ct0-checkbox-checked": checked,
        "ct0-checkbox-disabled": disabled,
        className,
      })}
      style={style}
    >
      <RcCheckbox
        style={{ fontSize }}
        disabled={disabled}
        prefixCls="ct0-checkbox"
        checked={checked}
        onChange={(e) => onChange?.(value, (e!.target as any).checked)}
      />
      {label}
    </label>
  );
}

function Group({
  style,
  className,
  border,
  value,
  options,
  disabled,
  onChange,
}: CheckboxGroupProps) {
  const handler = (v: string | number | undefined, checked: boolean) => {
    const newV = v!;
    if (checked) {
      onChange?.([...value, newV]);
    } else {
      onChange?.([...value.filter((i) => i != newV)]);
    }
  };

  return (
    <div
      className={classnames("ct0-checkbox-wrapper", className)}
      style={style}
    >
      {options.map((i, index) => (
        <Checkbox
          key={index}
          border={border}
          checked={value.includes(i.value)}
          value={i.value}
          disabled={disabled || i.disabled}
          label={i.label}
          onChange={handler}
        />
      ))}
    </div>
  );
}
